package com.jf.net.interceptor;

import android.util.Log;

import androidx.annotation.NonNull;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Locale;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * RequestInterceptor
 * @author JackyFlame
 * @time 2023/10/20 14:50
 * @description
 */
public class LogInterceptor implements Interceptor {
    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        long t1 = System.nanoTime();
        Request request = chain.request();
        Log.d("JF_NET", String.format("Sending request %s on Connection: %s %n Headers: %s ",
                request.url(),
                chain.connection(),
                request.headers()));
        Response response = null;
        try{
            response = chain.proceed(request);
        }catch (IOException e){
            Log.i("JF_NET", String.format("Sending request %s ERROR: %S", request.url(), e.getMessage()));
        }
        long t2 = System.nanoTime();
        if(response == null){
            return new Response.Builder()
                    .body(ResponseBody.create(MediaType.parse("application/json; charset=UTF-8"), ""))
                    .protocol(Protocol.HTTP_2)
                    .code(504)
                    .message("chain.proceed(request) return null")
                    .request(request)
                    .build();
        }
        Log.d("JF_NET", String.format(Locale.CHINA,
                "Received response for " +
                        "%s in %.1fms %n" +
                        "Response Status Code: %s %n" +
                        "Response Headers: %s %n" +
                        "Response CacheControl:%s %n" +
                        "Response Body :%s %n" +
                        "Is From Cached Response: %s %n",
                request.url(),
                (t2 - t1) / 1e6d,
                response.code(),
                response.headers(),
                response.cacheControl(),
                "Response{protocol= " + response.protocol() + ",code=" + response.code()
                        + ",message=" + response.message() + "}",
                response.cacheResponse() == response.networkResponse()));
        if (response.code() != 200) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                Charset UTF8 = StandardCharsets.UTF_8;
                BufferedSource source = responseBody.source();
                source.request(Long.MAX_VALUE);
                Buffer buffer = source.buffer();

                Charset charset = UTF8;
                MediaType contentType = responseBody.contentType();
                if (contentType != null) {
                    try {
                        charset = contentType.charset(UTF8);
                    } catch (UnsupportedCharsetException e) {
                        Log.e("JF_NET", "UnsupportedCharsetException Error" + e.getMessage());
                    }
                }
                String respBody = buffer.clone().readString(charset);
                Log.i("JF_NET", String.format(" >>> Response Body Content :%s %n", respBody));
            }

        }

        return response;
    }
}
